﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XiangDongClub.AllProxy;
using XiangDongClub.BLL;
using XiangDongClub.Common;
using XiangDongClub.Model;
using  Frameworks = Framework;

namespace XiangDongClub.Activity.Controllers
{
    public class HomeController : Controller
    {

        private readonly ZTManager _ztManager = Proxy.ZTManager;
        private readonly AreaManager _areaManager = Proxy.AreaManager;
        private readonly HshManager _hshManager = Proxy.HshManager;
        private readonly UserManager _userManager = Proxy.UserManager;


        /// <summary>
        /// 单点登录授权
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string p) 
        {
            try
            {
                p = com.xwtec.xdjs.DesUtil3PClient.encode("15002884245", "xdjs");
                Log4NetObject.WriteInfo("掌厅单点登录,加密手机号：" + p);
                var phone = com.xwtec.xdjs.DesUtil3PClient.decode(p, "xdjs");//解码
                Log4NetObject.WriteInfo("掌厅单点登录,解密手机号：" + phone);
                if (!string.IsNullOrEmpty(phone))
                {
                    var fuwuId = "";
                    if (_hshManager.HeshenghuoLogin(phone, out fuwuId))
                    {
                        SessionHelper.Add("p", phone);
                        //CookieHelper.Add("p", Frameworks.Utilities.EncryptDES(phone));
                        return Redirect("/Home/XdjsIndex");
                    }
                }
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("授权获取手机号失败，错误信息：{0}", ex.Message));
            }
            return View();
           
        }


        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ActionResult XdjsIndex()
        {
            var model = new List<TicketModel>();
            var phone = GetUserPhone();
            if (string.IsNullOrEmpty(phone))
                return Redirect("/Home/Index");
            try
            {
                model = _ztManager.GetTicketByPhone(phone);
                ViewBag.Ticket = _ztManager.GetAllTicke();
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户进入首页失败，错误信息：{1}", phone, ex.Message));
            }
            ViewBag.Pid = phone;
            return View(model);
        }

        #region 免费体验馆
        /// <summary>
        /// 免费体验馆
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public ActionResult FreeShop(int cityId = 1)
        {
            var model = new List<ZT_Shop>();
            var phone = GetUserPhone();
            
            var areaList = new List<Area>();
            var shopId = 0;
            try
            {
                var ticket = _ztManager.GetTicket(phone, 1).FirstOrDefault();
                if (ticket != null)
                    shopId = ticket.ShopId;

                model = _ztManager.GetShopByParams(cityId, 1);//获取当前场馆
                areaList = _areaManager.GetAllCitys(0);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户获取免费体验馆失败，错误信息：{1}",phone,ex.Message));
            }
            ViewBag.TicketShopId = shopId;
            ViewBag.CityList = areaList;
            ViewBag.CityId = cityId;
            return View(model);
        }

        /// <summary>
        /// 领取免费体验券
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public JsonResult RecFreeTicket(string phone, int shopId)
        {
            if(string.IsNullOrWhiteSpace(phone))
                return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);

            try
            {
                var recCount = _ztManager.GetTicket(phone, 1).Count();
                if (recCount >= 1)
                    return Json(new { Success = false,Code=1, Message = "每人限领一张！" }, JsonRequestBehavior.AllowGet);

                var sur = _ztManager.GetShopTicketSurCount(shopId, 1);
                if(sur <=0)
                    return Json(new { Success = false, Code = 2, Message = "当前场馆体验券已领完！" }, JsonRequestBehavior.AllowGet);

                ZT_RecTicket ticket = new ZT_RecTicket();
                ticket.Phone = phone;
                ticket.ShopId = shopId;
                ticket.TicketCode = _ztManager.GenerateRandomCode(10);
                ticket.CurType = 1;
                ticket.RecTime = DateTime.Now;
                ticket.State = 1;
                _ztManager.AddTicket(ticket);
                Log4NetObject.WriteInfo(string.Format("{0}用户领取免费体验券成功，领取场馆：{1}", phone, shopId));
                return Json(new { Success = true, Code = 0, Message = "领取体验券成功！" }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户领取免费体验券失败，错误信息：{1}",phone, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }

        #endregion


        #region  公用方法

        public JsonResult PageClick(string phone, int pageType)
        {
            try
            {
                if(string.IsNullOrEmpty(phone))
                    return Json(new { Success = false }, JsonRequestBehavior.AllowGet);

                var click = _ztManager.GetClickByPhone(phone, pageType);
                if(click==null)
                {
                    ZT_PageClick pc = new ZT_PageClick();
                    pc.Phone = phone;
                    pc.PageType = pageType;
                    pc.CreateTime = DateTime.Now;
                    pc.LastTime = DateTime.Now;
                    _ztManager.AddPageClick(pc);
                }
                else
                {
                    click.LastTime = DateTime.Now;
                    _ztManager.UpdatePageClick(click);
                }
                return Json(new { Success = true }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户添加页面点击记录失败，错误信息：{1}",phone, ex.Message));
            }
            return Json(new { Success = false }, JsonRequestBehavior.AllowGet);

        }

        /// <summary>
        /// 获取场馆详细信息
        /// </summary>
        /// <param name="shopId">场馆Id</param>
        /// <param name="curType">当前场馆类型1.免费 2.好礼 3.豪礼</param>
        /// <returns></returns>
        public JsonResult GetShopDetails(int shopId, int curType = 1)
        {
            try
            {
                if (shopId <= 0)
                    return Json(new { Success = false, Message = "当前场馆不存在，请稍后再试！" }, JsonRequestBehavior.AllowGet);

                var shop = _ztManager.GetShopDetailsByShopId(shopId, curType);
                return Json(new { Success = true, Message = shop }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("用户获取体验券详情失败，错误信息：{0}", ex.Message));
            }

            return Json(new { Success = false, Message = "当前场馆不存在，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 好礼加油站
        /// <summary>
        /// 好礼加油站
        /// </summary>
        /// <returns></returns>
        public ActionResult YearsShop(int cityId=1)
        {
            var model = new List<ZT_Shop>();
            var phone = GetUserPhone();
            var areaList = new List<Area>();
            var shopId = 0;
            try
            {
                var ticket = _ztManager.GetTicket(phone, 2).FirstOrDefault();
                if (ticket != null)
                    shopId = ticket.ShopId;
                model = _ztManager.GetShopByParams(cityId, 2);//获取当前场馆
                areaList = _areaManager.GetAllCitys(0);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户获取好礼加油体验馆失败，错误信息：{1}", phone, ex.Message));
            }
            ViewBag.TicketShopId = shopId;
            ViewBag.CityList = areaList;
            ViewBag.CityId = cityId;
            return View(model);
        }

        public JsonResult GetShopListMethod(int cityId,int pageType)
        {
            var model = new List<ZT_Shop>();
            try
            {
                model = _ztManager.GetShopByParams(cityId, pageType);//获取当前场馆
                return Json(new { Success = true, CityId = cityId, Message = model }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("用户根据城市获取体验馆失败，场馆类型：{2}，城市：{0}，错误信息：{1}", cityId, ex.Message, pageType));
            }
            return Json(new { Success = false, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 领取好礼加油体验券
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public JsonResult RecYearTicket(string phone, int shopId)
        {
            if (string.IsNullOrEmpty(phone))
                return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);

            try
            {
                var recCount = _ztManager.GetTicket(phone, 2).Count();
                if (recCount >= 1)
                    return Json(new { Success = false, Code = 1, Message = "每人限领一张！" }, JsonRequestBehavior.AllowGet);

                var sur = _ztManager.GetShopTicketSurCount(shopId, 2);
                if (sur <= 0)
                    return Json(new { Success = false, Code = 2, Message = "当前场馆体验券已领完！" }, JsonRequestBehavior.AllowGet);

                int isorder = _ztManager.GetOrderShipCount(phone);//查询用户是否订购
                //if (isorder <= 0)
                //{
                //    Log4NetObject.WriteInfo(string.Format("查询用户是否订购手机报开始时间：{0}", DateTime.Now));
                //    var password = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_password");            //密码    为预定字符串
                //    var username = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_username");                  //用户名   区分不同用户标识(获取方式需要向手机报申请)
                //    var businessId = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_businessId");               //业务ID  获取对应的业务id  
                //    _ztManager.SyncSjbUserAct(password, username, int.Parse(businessId),phone); //手机报用户订购关系同步
                //    Log4NetObject.WriteInfo(string.Format("查询用户是否订购手机报结束时间：{0}", DateTime.Now));
                //    isorder = _ztManager.GetOrderShipCount(phone);//同步后再次查询用户是否订购
                //}
                if(isorder<=0)
                    return Json(new { Success = false, Code = 3, Message = "请您先进行业务订购，方可领取！" }, JsonRequestBehavior.AllowGet);


                ZT_RecTicket ticket = new ZT_RecTicket();
                ticket.Phone = phone;
                ticket.ShopId = shopId;
                ticket.TicketCode = _ztManager.GenerateRandomCode(10);
                ticket.CurType = 2;
                ticket.RecTime = DateTime.Now;
                ticket.State = 1;
                _ztManager.AddTicket(ticket);
                Log4NetObject.WriteInfo(string.Format("{0}用户领取好礼加油体验券成功，领取场馆：{1}", phone, shopId));
                return Json(new { Success = true, Code = 0, Message = "领取体验券成功！" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户领取好礼加油体验券失败，错误信息：{1}", phone, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }


        #endregion

        #region 豪礼助力体验券

        /// <summary>
        /// 豪礼助力站
        /// </summary>
        /// <returns></returns>
        public ActionResult CurrentShop(int cityId=1)
        {
            var model = new List<ZT_Shop>();
            var phone = GetUserPhone();
            var areaList = new List<Area>();
            try
            {
                var ticket = _ztManager.GetTicket(phone, 3).FirstOrDefault();
                if (ticket != null)
                    return Redirect("/Home/CurrentUser?shopId=" + ticket.ShopId);

               model = _ztManager.GetShopByParams(cityId, 3);//获取当前场馆
               areaList = _areaManager.GetAllCitys(0);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户获取豪礼助力体验馆失败，错误信息：{1}", phone, ex.Message));
            }
            ViewBag.CityList = areaList;
            ViewBag.CityId = cityId;
            return View(model);
        }
        /// <summary>
        /// 领取豪礼助力体验券
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public JsonResult RecCurTicket(string phone, int shopId)
        {
            if (string.IsNullOrEmpty(phone))
                return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);

            try
            {
                var recCount = _ztManager.GetTicket(phone, 3).Count();
                if (recCount >= 1)
                    return Json(new { Success = true, Code = 1, Message = shopId }, JsonRequestBehavior.AllowGet);

                var sur = _ztManager.GetShopTicketSurCount(shopId, 3);
                if (sur <= 0)
                    return Json(new { Success = false, Code = 2, Message = "当前场馆体验券已领完！" }, JsonRequestBehavior.AllowGet);

                int isorder = _ztManager.GetOrderShipCount(phone);//查询用户是否订购
                //if (isorder <= 0)
                //{
                //    Log4NetObject.WriteInfo(string.Format("查询用户是否订购手机报开始时间：{0}", DateTime.Now));
                //    var password = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_password");            //密码    为预定字符串
                //    var username = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_username");                  //用户名   区分不同用户标识(获取方式需要向手机报申请)
                //    var businessId = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_businessId");               //业务ID  获取对应的业务id  
                //    _ztManager.SyncSjbUserAct(password, username, int.Parse(businessId), phone); //手机报用户订购关系同步
                //    Log4NetObject.WriteInfo(string.Format("查询用户是否订购手机报结束时间：{0}", DateTime.Now));
                //    isorder = _ztManager.GetOrderShipCount(phone);//同步后再次查询用户是否订购
                //}
                if (isorder <= 0)
                    return Json(new { Success = false, Code = 3, Message = "请您先进行业务订购，方可领取！" }, JsonRequestBehavior.AllowGet);


                ZT_RecTicket ticket = new ZT_RecTicket();
                ticket.Phone = phone;
                ticket.ShopId = shopId;
                ticket.TicketCode = _ztManager.GenerateRandomCode(10);
                ticket.CurType = 3;
                ticket.RecTime = DateTime.Now;
                ticket.State = 0;
                _ztManager.AddTicket(ticket);
                Log4NetObject.WriteInfo(string.Format("{0}用户领取豪礼加油体验券成功，领取场馆：{1}", phone, shopId));
                return Json(new { Success = true, Code = 0, Message = shopId }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户领取好礼加油体验券失败，错误信息：{1}", phone, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 豪礼用户助力
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public ActionResult CurrentUser(int shopId)
        {
            var model = new ZT_Shop();
            var phone = GetUserPhone();
            var helpcount = 0;
            try
            {
                model = _ztManager.GetShopDetailsByShopId(shopId, 3);
                helpcount = _ztManager.GetFriendsHelpByPhone(phone).Count();
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户获取豪礼助力个人页面失败，错误信息：{1}", phone, ex.Message));
            }
            ViewBag.SignPhone = Framework.Utilities.EncryptDES(phone); 
            ViewBag.HelpCount = helpcount;
            return View(model);
        }

        public JsonResult RecCurrentTicket(string phone)
        {
            try
            {
                var ticket = _ztManager.GetTicket(phone, 3).FirstOrDefault();
                if(ticket==null)
                    return Json(new { Success = false, Code = 0, Message = "系统错误，请稍后再试！" }, JsonRequestBehavior.AllowGet);
                if(ticket.State==1)
                    return Json(new { Success = false, Code = 1, Message = "请勿重复领取！" }, JsonRequestBehavior.AllowGet);

                ticket.State = 1;
                ticket.RecTime = DateTime.Now;
                _ztManager.UpdateTicket(ticket);
                return Json(new { Success = true, Code = 0, Message = "领取成功！" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户领取豪礼助力体验券失败，错误信息：{1}", phone, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 豪礼助力分享页面
        /// </summary>
        /// <param name="p"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public ActionResult CurrentShare(string p,string openid="")
        {
            var authURL = System.Configuration.ConfigurationManager.AppSettings["WechatAuthUrl"].ToString();
            if (string.IsNullOrEmpty(openid))
                return Redirect(authURL + "?back=" + Request.Url.AbsoluteUri);

            var model = new ZT_Shop();
            var helpcount = 0;
            var phone = "";
            try
            {
                phone = Framework.Utilities.DecryptDES(p);
                var ticket = _ztManager.GetTicket(phone, 3).FirstOrDefault() ;
                model = _ztManager.GetShopDetailsByShopId(ticket.ShopId, 3);
                helpcount = _ztManager.GetFriendsHelpByPhone(phone).Count();
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户帮助{1}获取豪礼体验分享页面失败，错误信息：{1}", openid, phone, ex.Message));
            }
            ViewBag.HelpCount = helpcount;
            return View(model);
        }

        /// <summary>
        /// 好友助力
        /// </summary>
        /// <param name="p"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public JsonResult FightingMethod(string p,string openId)
        {
            var phone = "";
            try
            {
                phone = Framework.Utilities.DecryptDES(p);
                if(phone.Length<11 || openId.Length < 10)
                    return Json(new { Success = false, Code = 1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
                var fcount = _ztManager.GetFriendsHelpByPhone(phone).Count();
                if(fcount >= 30)
                    return Json(new { Success = false, Code = 2, Message = "好友已完成助力，谢谢参与！" }, JsonRequestBehavior.AllowGet);
                var ucount = _ztManager.GetFriendHelpByOpenid(openId).Count();
                if(ucount > 0)
                    return Json(new { Success = false, Code = 3, Message = "每个用户只能为好友加油一次！" }, JsonRequestBehavior.AllowGet);


                ZT_FriendsHelp fh = new ZT_FriendsHelp();
                fh.OpenId = openId;
                fh.Phone = phone;
                fh.CreateTime = DateTime.Now;
                var help = _ztManager.AddFriendsHelp(fh);
                if(help==null)
                    return Json(new { Success = false, Code = 4, Message = "为好友加油失败，请稍后再试！" }, JsonRequestBehavior.AllowGet);
               
                return Json(new { Success = true, Code = 0, Message = "为好友加油成功！" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户为{1}助力失败，错误信息：{2}",openId, phone, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }

        #endregion



        public ActionResult RecTicketSuccess()
        {
            return View();
        }

        public string GetUserPhone()
        {
            return SessionHelper.GetSession("p");
        }

    }
}